import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { message, Form, Input, Button, Radio } from 'antd';
import React, { useState } from 'react';
import { ProFormText, LoginForm } from '@ant-design/pro-form';
import { history, useModel, useRequest } from 'umi';
import styles from './index.less';
import defaultSettings from '../../../config/defaultSettings';
import { setToken } from '@/utils/auth';

const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [isShowRegister, setIsShowRegister] = useState(false)

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();

    if (userInfo) {
      await setInitialState((s) => ({ ...s, currentUser: userInfo }));
    }
  };

  const { run: loginApi } = useRequest((data) => ({
    url: '/api/auth/login',
    method: 'post',
    data
  }), {
    manual: true
  })

  const handleSubmit = async (values: API.LoginParams) => {
    const msg = await loginApi({ ...values })
    if (msg && msg.token) {
      setToken(msg.token)
      message.success('登录成功');
      await fetchUserInfo();
      if (!history) return;
      const { query } = history.location;
      const { redirect } = query as {
        redirect: string;
      };
      history.push(redirect || '/');
    } else {
      message.error('登录失败');
    }
  };

  const { run: registerApi, loading: registerLoading } = useRequest((data) => ({
    url: '/api/auth/register',
    method: 'post',
    data
  }), {
    manual: true
  })

  const onFinish = async (values: any) => {
    await registerApi(values)
    setIsShowRegister(false)
  };
  
  if (isShowRegister) {
    return (
      <div className={styles.container}>
        <div className={styles.content}>
          <Form autoComplete="off" onFinish={onFinish} style={{ width: "328px", margin: '0 auto' }}>
            <div style={{ fontSize: '33px', fontWeight: 600, color: 'rgba(0, 0, 0, 0.85)', textAlign: 'center' }}>{defaultSettings.title}</div>
            <div style={{ height: '20px' }} />
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入用户名!' }]}
            >
              <Input size='large' prefix={<UserOutlined className={styles.prefixIcon} />} placeholder='请输入用户名' />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password size='large' prefix={<LockOutlined className={styles.prefixIcon} />} placeholder='请输入密码' />
            </Form.Item>
            <Form.Item
              name="passwordAgain"
              rules={[
                { required: true, message: '请再次输入密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password size='large' prefix={<LockOutlined className={styles.prefixIcon} />} placeholder='请再次输入密码' />
            </Form.Item>
            <Form.Item name="roleId" rules={[{ required: true, message: '请选择用户权限' }]}>
              <Radio.Group>
                <Radio value="3">学生</Radio>
                <Radio value="2">教师</Radio>
                <Radio value="1">管理员</Radio>
              </Radio.Group>
            </Form.Item>
            <div className={styles.register}>
              <span onClick={() => { setIsShowRegister(false) }}>立即登录</span>
            </div>
            <Form.Item>
              <Button size='large' loading={registerLoading} type="primary" htmlType="submit" block>
                注册
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    )
  }

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          title={defaultSettings.title as string}
          initialValues={{
            username: 'admin',
            password: 'admin',
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <div style={{ height: '20px' }} />
          <ProFormText
            name="username"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined className={styles.prefixIcon} />,
            }}
            placeholder={'用户名: admin or user'}
            rules={[
              {
                required: true,
                message: '用户名是必填项！',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined className={styles.prefixIcon} />,
            }}
            placeholder={'密码: admin'}
            rules={[
              {
                required: true,
                message: '密码是必填项！',
              },
            ]}
          />
          <div className={styles.register}>
            <span onClick={() => { setIsShowRegister(true) }}>立即注册</span>
          </div>
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
